Class類別可以定義一個物件(Object)抽象的屬性和方法,
Class是ES6以後才有的,其實大部分的功能ES5都做得到(使用prototype)
只是這樣寫更漂亮,更偏向物件導向。
跟其他物件導向(OOP)的概念一樣,擁有三大特性:
- 封裝(Encapsulation)隱藏部分細節,外界只能訪問無法修改
- 繼承 (Inherentance) 可以繼承其他物件,並擁有繼承對象的所有屬性
- 多型 (Polymorphism)繼承來的方法可以有不同的做法。(如鳥跟雞都繼承了動物類別的飛動作,但兩者的非不一樣,雞飛不起來。)
其他操作細節:
引用改編自:TS類別
環遊非洲第04天:Q
猜猜肯亞最熱的月份最高溫度可以到幾度?(看動物大遷徙最有名的肯亞!)
A. 40-45度C
B. 30-35度C
C. 25-27度C
D. 15-20度C
Class透過extends實現繼承,並在contructor()裡面使用super()
呼叫父類的構造函數。
要先使用super()才能使用this
//改寫了一下我的障礙物
class Obstacle {
    constructor(x){
     this.x = x
    }
  
    Update () {
    return 'I am a obstacle'
  }
}
//不會報錯
class ChildObstacle extends Obstacle{}
let childObstacle  = new ChildObstacle()
//會報錯,因為contructor裡面一定要用super()
//Uncaught ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
class ChildObstacle2 extends Obstacle{
    constructor(){
    }
}
let childObstacle  = new ChildObstacle2()
class ChildObstacle3 extends Obstacle{
    constructor(x,y){
        this.y = y //創建實例的時候會報錯,VM194:3 Uncaught ReferenceError: Must call super constructor in derived class before accessing 'this'
        super(x)
        this.y = y
    }
}
let childObstacle  = new ChildObstacle3()
加上static 修飾符的方法是靜態的,不會被實例繼承,
但是可以被子類繼承。(抽象類別)
//改寫了一下我的障礙物
class Obstacle {
    //靜態屬性
  static width = 30
  
  //靜態方法
  static Update () {
    return 'I am a obstacle'
  }
}
//1.不會被實例繼承
let newObstacles = new Obstacle
newObstacles.Update()
//Uncaught TypeError: newObstacles.Update is not a function
newObstacles.width
//Uncaught SyntaxError: Unexpected identifier 'width'
//2.可以被子類繼承
class ChildObstacle extends Obstacle{}
ChildObstacle.Update()
//'I am a obstacle'
ChildObstacle.width
//30
Class裡面的屬性基本都是public,要加上私有屬性和方法,使用#前綴。
不會被子類繼承,
要獲取的話,可以在父類裡面定義讀取的方法。
class Obstacle {
  #x = 1;
  #y() {
    console.log('I am an obstacle');
  }
  //定義私有屬性讀取的方法
  getX(){
    return this.#x
  }
}
class ChildObstacle extends Obstacle {
  constructor() {
    super();
    console.log(this.#x); // 創建實例時error: Uncaught SyntaxError: Private field '#x' must be declared in an enclosing class
    this.#y(); //創建實例時 error: Uncaught SyntaxError: Private field '#x' must be declared in an enclosing class
    console.log(this.getX()); // return : 1
  }
}
環遊非洲第04天:A
答案是C!最熱的月份是三月,也不到30度
因為肯亞全境大部分是高原和高山,雖然被赤道橫貫,但氣候卻是很怡人的喔!

關於類的這兩篇, 我還沒有Cover到和prototype的比較、mixin的使用
還有in運算符、this指向、generator用法...
寫不完啦!
之後再回來補充!
以下這篇文章並沒有更新Static,已經被採用了。